package com.wedo.mall.activity.user;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.widget.ETitleBar;
import com.wedo.mall.R;
import com.wedo.mall.entity.City;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class CreateAddressActivity extends EActivity {

    @BindView(R.id.title_bar) ETitleBar title_bar;
    @BindView(R.id.et_address) EditText et_address;
    @BindView(R.id.et_phone) EditText et_phone;
    @BindView(R.id.et_recipient) EditText et_recipient;
    @BindView(R.id.tv_pcc) TextView tv_pcc;

    private OptionsPickerView pvOptionsAddress;
    public ArrayList<City> provinces = new ArrayList<>();
    public ArrayList<ArrayList<City>> cities = new ArrayList<>();
    public ArrayList<ArrayList<ArrayList<City>>> regions = new ArrayList<>();

    private String temProvinceId = null;
    private String temCityId= null;
    private String temCountyId= null;

    @Override
    protected int layout() {
        return R.layout.activity_create_address;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        title_bar.setForwardText(getResources().getString(R.string.save));
        title_bar.showForwordTv();
        title_bar.setForwardTextColor(getResources().getColor(R.color.user_addresslist_font));
        init();
        buildOptionsPickerView();
    }

    private void init(){
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getAssets().open("Malaysia.json");
            InputStreamReader reader = new InputStreamReader(is,"UTF-8");
            char[] buf = new char[1024];
            while (reader.read(buf) !=-1){
                sb.append(buf);
            }
            is.close();

            /**省*/
            JSONArray pArray = new JSONArray(sb.toString());
            int pLength = pArray.length();
            for (int i = 0; i < pLength; i++) {
                JSONObject pObject = pArray.getJSONObject(i);
                City p = new City();
                p.id = pObject.getString("id");
                p.name = pObject.getString("name");


                /**市*/
                JSONArray cArray = pObject.getJSONArray("child");
                int cLength = cArray.length();
                ArrayList<City> cList = new ArrayList<>(cLength);
                ArrayList<ArrayList<City>> cChild = new ArrayList<>();

                for (int j = 0;j <cLength;j++){

                    JSONObject cObject = cArray.getJSONObject(j);

                    City c = new City();
                    c.id = cObject.getString("id");
                    c.name = cObject.getString("name");
                    cList.add(c);

                    /**区*/
                    if(!cObject.has("child") || cObject.isNull("child")) {
                        cChild.add(new ArrayList<City>(0));
                        continue;

                    }
                    JSONArray rArray = cObject.getJSONArray("child");
                    int rLength = rArray.length();
                    ArrayList<City> rList = new ArrayList<>(rLength);
                    for (int k = 0; k < rLength; k++) {
                        JSONObject rObject = rArray.getJSONObject(k);

                        City r = new City();
                        r.id = rObject.getString("id");
                        r.name = rObject.getString("name");
                        rList.add(r);
                    }
                    cChild.add(rList);
                }

                provinces.add(p);
                cities.add(cList);
                regions.add(cChild);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    public void buildOptionsPickerView() {

        //条件选择器
        pvOptionsAddress = new OptionsPickerView.Builder(CreateAddressActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                StringBuilder sb = new StringBuilder();

                /**省*/
                City province = provinces.get(options1);
                /**市*/
                City city = cities.get(options1).get(option2);
                /**区*/
                sb.append(province.name).append(" ").append(city.name);
                if(!regions.get(options1).get(option2).isEmpty()) {
                    City region = regions.get(options1).get(option2).get(options3);
                    sb.append(" ").append(region.name);

                    temCountyId = region.id;
                }

                Log.i("Address",sb.toString());

                tv_pcc.setText(sb.toString());

                temProvinceId = province.id;
                temCityId = city.id;

            }
        }).setTitleText(getResources().getString(R.string.address))
                .setTitleColor(getResources().getColor(R.color.e_purple))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.e_purple))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.e_purple))//取消按钮文字颜色
                .build();

        pvOptionsAddress.setPicker(provinces, cities, regions);

    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setCursorVisible(true);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputManager = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }


    private void addConsignee(){
        if(et_recipient.getText().toString().equals("")){
            toast(R.string.address_recipient_toast);
        }else if(et_phone.getText().toString().equals("")){
            toast(R.string.address_phone_toast);
        }else if(tv_pcc.getText().toString().equals("")){
            toast(R.string.address_pcc_toast);
        }else if( et_address.getText().toString().equals("")){
            toast(R.string.address_address_toast);
        }else{
            loading();
            Map<String,String> params = new HashMap<>();
            params.put("consignee",et_recipient.getText().toString());
            params.put("province",temProvinceId);
            params.put("city",temCityId);
            if(temCountyId != null){
                params.put("county",temCountyId);
            }
            params.put("address",et_address.getText().toString());
            params.put("telephone",et_phone.getText().toString());
            Observable<EResponse> observable = EClient.with().api().post(EApi.USER_ADDCONSIGNEE,params);
            EClient.with().observer(observable, new EObserver() {
                @Override
                public void successful(EResponse response) {

                    dismiss();
                    defaultFinish();
                }

                @Override
                public void failure(String msg) {
                    dismiss(msg);
                }
            });
        }

    }

    @OnClick(R.id.tv_forward)
    protected void onSaveClick(){
        addConsignee();
    }

    @OnClick(R.id.rl_address)
    protected void onEditAddressClick(){
        showSoftInputFromWindow(this,et_address);
    }

    @OnClick(R.id.rl_phone)
    protected void onEditPhoneClick(){
        showSoftInputFromWindow(this,et_phone);
    }

    @OnClick(R.id.rl_recipient)
    protected void onEditRecipientClick(){
        showSoftInputFromWindow(this,et_recipient);
    }

    @OnClick(R.id.rl_province)
    protected void onProvinceClick(){
        pvOptionsAddress.show();
    }
}
